const express = require('express');
const router = express.Router();
const Food = require('../models/Food');

// ==================== 美食推荐 API ====================

// 获取美食列表
router.get('/', async (req, res) => {
  try {
    const {
      page = 1,
      limit = 20,
      category,
      sortBy = 'rating',
      sortOrder = 'desc',
      search,
      minPrice,
      maxPrice,
      location,
      isRecommended,
      isHot
    } = req.query;

    const skip = (page - 1) * limit;
    const limitNum = Math.min(parseInt(limit), 50);

    // 构建查询条件
    let query = { isAvailable: true };

    if (category && category !== 'all') {
      query.category = category;
    }

    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } },
        { 'restaurant.name': { $regex: search, $options: 'i' } },
        { tags: { $in: [new RegExp(search, 'i')] } }
      ];
    }

    if (minPrice || maxPrice) {
      query.price = {};
      if (minPrice) query.price.$gte = parseFloat(minPrice);
      if (maxPrice) query.price.$lte = parseFloat(maxPrice);
    }

    if (location) {
      query['restaurant.address'] = { $regex: location, $options: 'i' };
    }

    if (isRecommended === 'true') {
      query.isRecommended = true;
    }

    if (isHot === 'true') {
      query.isHot = true;
    }

    // 构建排序条件
    let sort = {};
    const order = sortOrder === 'desc' ? -1 : 1;

    switch (sortBy) {
      case 'price':
        sort.price = order;
        break;
      case 'rating':
        sort.rating = order;
        sort.reviewCount = -1;
        break;
      case 'sales':
        sort.salesCount = order;
        break;
      case 'created':
        sort.createdAt = order;
        break;
      default:
        sort.rating = -1;
        sort.salesCount = -1;
    }

    const foods = await Food.find(query)
      .sort(sort)
      .skip(skip)
      .limit(limitNum)
      .lean();

    const total = await Food.countDocuments(query);

    res.json({
      success: true,
      data: foods,
      pagination: {
        page: parseInt(page),
        limit: limitNum,
        total,
        pages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取美食列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取美食列表失败',
      error: error.message
    });
  }
});

// 获取美食详情
router.get('/:foodId', async (req, res) => {
  try {
    const { foodId } = req.params;

    const food = await Food.findById(foodId);
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '美食不存在'
      });
    }

    res.json({
      success: true,
      data: food
    });

  } catch (error) {
    console.error('获取美食详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取美食详情失败',
      error: error.message
    });
  }
});

// 获取推荐美食
router.get('/recommend/popular', async (req, res) => {
  try {
    const { limit = 10 } = req.query;

    const foods = await Food.getPopularFoods(parseInt(limit));

    res.json({
      success: true,
      data: foods
    });

  } catch (error) {
    console.error('获取推荐美食失败:', error);
    res.status(500).json({
      success: false,
      message: '获取推荐美食失败',
      error: error.message
    });
  }
});

// 按分类获取美食
router.get('/category/:category', async (req, res) => {
  try {
    const { category } = req.params;
    const { limit = 20 } = req.query;

    const foods = await Food.getFoodsByCategory(category, parseInt(limit));

    res.json({
      success: true,
      data: foods
    });

  } catch (error) {
    console.error('按分类获取美食失败:', error);
    res.status(500).json({
      success: false,
      message: '按分类获取美食失败',
      error: error.message
    });
  }
});

// 搜索美食
router.get('/search/:keyword', async (req, res) => {
  try {
    const { keyword } = req.params;
    const { limit = 20 } = req.query;

    const foods = await Food.searchFoods(keyword, parseInt(limit));

    res.json({
      success: true,
      data: foods
    });

  } catch (error) {
    console.error('搜索美食失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索美食失败',
      error: error.message
    });
  }
});

// 获取美食分类统计
router.get('/stats/categories', async (req, res) => {
  try {
    const stats = await Food.aggregate([
      { $match: { isAvailable: true } },
      {
        $group: {
          _id: '$category',
          count: { $sum: 1 },
          avgRating: { $avg: '$rating' },
          avgPrice: { $avg: '$price' }
        }
      },
      { $sort: { count: -1 } }
    ]);

    res.json({
      success: true,
      data: stats
    });

  } catch (error) {
    console.error('获取分类统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分类统计失败',
      error: error.message
    });
  }
});

// ==================== 美食评价 API ====================

// 添加美食评价
router.post('/:foodId/reviews', async (req, res) => {
  try {
    const { foodId } = req.params;
    const {
      rating,
      content,
      images = []
    } = req.body;

    // 简化用户信息，实际项目中应该从token获取
    const userId = '6872826501b094a9bfe8e055';
    const userName = '旅行爱好者';
    const userAvatar = null;

    const food = await Food.findById(foodId);
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '美食不存在'
      });
    }

    const review = {
      userId,
      userName,
      userAvatar,
      rating: parseInt(rating),
      content,
      images,
      createdAt: new Date()
    };

    await food.addReview(review);

    res.status(201).json({
      success: true,
      message: '评价添加成功',
      data: review
    });

  } catch (error) {
    console.error('添加评价失败:', error);
    res.status(500).json({
      success: false,
      message: '添加评价失败',
      error: error.message
    });
  }
});

// 点赞评价
router.post('/:foodId/reviews/:reviewId/helpful', async (req, res) => {
  try {
    const { foodId, reviewId } = req.params;

    const food = await Food.findById(foodId);
    if (!food) {
      return res.status(404).json({
        success: false,
        message: '美食不存在'
      });
    }

    const review = food.reviews.id(reviewId);
    if (!review) {
      return res.status(404).json({
        success: false,
        message: '评价不存在'
      });
    }

    review.helpful += 1;
    await food.save();

    res.json({
      success: true,
      message: '点赞成功',
      data: { helpful: review.helpful }
    });

  } catch (error) {
    console.error('点赞失败:', error);
    res.status(500).json({
      success: false,
      message: '点赞失败',
      error: error.message
    });
  }
});

module.exports = router; 